<?php
class Controller_Cart extends Controller_Abstract
{
    public $ship=array('email'=>'','gender'=>'', 'firstname'=>'','lastname'=>'','company'=>'', 'street1'=>'','street2'=>'', 'phone'=>'', 'postalcode'=>'', 'country'=>'','cityname'=>'','stateorprovince'=>'');
    function __construct(){
        parent::__construct($this->_app);
        $this->store=Q::INI('store');
        $this->_view['store']=$this->store=Q::INI('store');
        if(empty($this->store)){
            return $this->_404();
        }
    }
    /******
     *  goods[goods_id]=array(goods_id,quantity,price,),
     *  ship=array(
     *  
     *          )     
     *  currency=
     *  amount=     
     *  shipment=
     *  payment=
     *  status=               
     *
     */              
    function _cart($k=null,$v=null){
        if(isset($_SESSION['cart'][$k])){
            if(is_null($v)){
                return $_SESSION['cart'][$k];
            }else{
                return $_SESSION['cart'][$k]=$v;
            }
        }else{
            if(!isset($_SESSION['cart'])){
                $this->_destroy();
            }
            return $_SESSION['cart'];
        }
    }
    /**
     * 初始化
     */         
    function _destroy(){
        $_SESSION['cart']=null;
        $_SESSION['cart']=array(
            'goods'=>array(),
            'ship'=>$this->ship,
            'currency'=>'',
            'amount'=>0,
            'shipment'=>'',
            'payment'=>'',
            'coupon'=>'',
            'status'=>0
        );
    }
    
    function _recalculate(){
//         $goods=Goods::find('goods_id in (?)',array_keys($_SESSION['cart']['goods']))->getAll();
        $a=0;
        if(isset($_SESSION['cart']['goods']) && count($_SESSION['cart']['goods'])){ 
            foreach($_SESSION['cart']['goods'] as $g){
              $t=$g['quantity']*$g['price'];
              $a+=$t;
            }
        }else{
            $_SESSION['cart']['goods']=array();
        }
        $_SESSION['cart']['amount']=$a;
    }
    
    function _buildOrder($order_fields_array=null){
    
        $order_id=Helper_Util::build_order_id();
        $amount=0;
        foreach($_SESSION['cart']['goods'] as $g){
            $t=$g['quantity']*$g['price'];
            $amount+=$t;
            $t=new Transaction;
            $t->changeProps(array(
               'store_id'=>$this->store['store_id'],
               'seller_id'=>$this->store['seller_id'],
               'customer_id'=>'',
               'order_id'=>$order_id,
               'goods_id'=>$g['goods_id'],
               'quantity'=>$g['quantity'],
               'price'=>$g['price'],
               'title'=>$g['title'],
               'currency'=>$_SESSION['cart']['currency'],
               'status_payment'=>'wait',
            ));
            $t->save();
        }
        $order=new Orders;
        $order_field=array(
             'store_id'=>$this->store['store_id'],
             'seller_id'=>$this->store['seller_id'],
             'customer_id'=>'',
             'order_id'=>$order_id,
             'ship_gender'=>$_SESSION['cart']['ship']['gender'],
             'ship_firstname'=>$_SESSION['cart']['ship']['firstname'],
             'ship_lastname'=>$_SESSION['cart']['ship']['lastname'],
             'ship_company'=>$_SESSION['cart']['ship']['company'],
             'ship_cityname'=>$_SESSION['cart']['ship']['cityname'],
             'ship_stateorprovince'=>$_SESSION['cart']['ship']['stateorprovince'],
             'ship_country'=>$_SESSION['cart']['ship']['country'],
//              'ship_countryname'=>$_SESSION['cart']['ship']['countryname'],
             'ship_street1'=>$_SESSION['cart']['ship']['street1'],
             'ship_street2'=>$_SESSION['cart']['ship']['street2'],
             'ship_postalcode'=>$_SESSION['cart']['ship']['postalcode'],
             'ship_phone'=>$_SESSION['cart']['ship']['phone'],
             'ship_email'=>$_SESSION['cart']['ship']['email'],
             'total_amount'=>$amount,
             'finel_amount'=>$amount,
             'shipping_cost'=>0,
             'finalvaluefee'=>0,
             'discount'=>0,
             'tax_cost'=>0,
             'payment_id'=>$_SESSION['cart']['payment'],
             'shipment_id'=>$_SESSION['cart']['shipment'],
             'status_payment'=>'wait',
        );
        if(count($order_fields_array)){
            if(isset($order_fields_array['memo'])){
                $order_field['memo']=$order_fields_array['memo'];
            }
        }
        $order->changeProps($order_field);
        $order->save();
        Helper_Cart::orderAdd($order_id);
        return $order_id;
    }
    /**
     * Check coupon  
     *  ABCDEF123     
     */         
    function _coupon($coupon=''){
        // check
        if(preg_match('/^[A-Za-z]{6}[0-9]{3}$/',$coupon)){
            $this->_cart('coupon',$coupon);
            return true;
        }else{
            return false;
        }
    }
    // 添加 
    function actionAdd(){
        $sg=$this->_cart('goods');
        $qs=$this->_context->post('quantity');
        if(is_array($qs)&&count($qs)){
            $mgs=Goods::find('goods_id in (?)',array_keys($qs))->getAll();
            foreach($mgs as $g){
                $q=(int)$qs[$g->goods_id];
                if(isset($sg[$g->goods_id])){
                    $sg[$g->goods_id]['quantity']+=$q;
                }else{
                    $sg[$g->goods_id]=array(
                        'goods_id'=>$g->goods_id,
                        'quantity'=>$q,
                        'price'=>$g->price,
                        'title'=>$g->name,
                    );
                }
            }
            $this->_cart('goods',$sg);
            $this->_recalculate();
            $this->_cart('status',1);
        }
        return $this->_redirect(url('cart')); 
    }
    /** 
     * List
     */    
    function actionIndex()
    {
        if($this->_cart('status')<=0){
            ' No products';
        }
        $sg=$this->_cart('goods');
        //更新数量
        if($this->_context->isPost() && count($this->_context->post('quantity'))){
            $qs=$this->_context->post('quantity');
            foreach($qs as $goods_id=>$q){
                $q=(int)$q;
                if($q<=0&&isset($sg[$goods_id])){
                    unset($sg[$goods_id]);
                }else{
                    $sg[$goods_id]['quantity']=$q;
                }
            }
            $this->_cart('goods',$sg);
            
            // 货币
            if(strlen($this->_context->post('currency'))){
                $this->_cart('currency',$this->_context->post('currency'));
            }
            $this->_recalculate();
            $this->_cart('status',1);
            return $this->_redirect(url('cart/checkout'));
        }
        if(count($sg)){
            $this->_view['goods']=Goods::find('goods_id in (?)',array_keys($sg))->getAll();
        }
        $this->_view['cart']=$this->_cart();
    }
    
    function actionRemoveGood(){
        $goods_id=$this->_context->query('goods_id');
        $sg=$this->_cart('goods');
        unset($sg[$goods_id]);
        $this->_cart('goods',$sg);
        $this->_recalculate();
        return $this->_redirect(url('cart'));
    }
    
    /****
     * 
     */
    function actionCheckout(){
        $this->_view['cart']=$this->_cart();
        if(!isset($this->_view['cart']['ship'])){
            $this->_view['cart']['ship']=$this->ship;
        }
        if($this->_context->isPost()){
            $ship=array_merge($this->_view['cart']['ship'],$_POST);
            // 收件人 ship 
            if(strlen($ship['email'])
                &&strlen($ship['firstname'])
                &&strlen($ship['lastname'])
                &&strlen($ship['street1'])
                &&strlen($ship['phone'])
                &&strlen($ship['postalcode'])
                &&strlen($ship['country'])
            ){
                $this->_cart('ship',$ship);
            }else{
                $this->_view['error']['ship']=1;
            }
            // 货币
            if(strlen($this->_context->post('currency'))){
                $this->_cart('currency',$this->_context->post('currency'));
            }
            // 配送方式
            if(strlen($this->_context->post('shipment'))){
                $this->_cart('shipment',$this->_context->post('shipment'));
            }else{
                $this->_view['error']['shipment']=1;
            }
            // 支付方式
            if(strlen($this->_context->post('payment'))){
                $this->_cart('payment',$this->_context->post('payment'));
            }else{
                $this->_view['error']['payment']=1;
            }
            if($this->_view['cart']['amount']>0){
                
            }else{
                $this->_view['error']['goods']=1;
            }
            // 附加 order 字段
            $order_fields_array=array(
                'memo'=>$this->_context->post('memo')
            );
            
            if(!isset($this->_view['error'])){
                $order_id=$this->_buildOrder($order_fields_array);
                if($order_id){
                    $this->_destroy();
                    return $this->_redirect(url('default/order',array('order_id'=>$order_id)));
                }
            }
        }
        
        $this->_view['country_array']=Helper_Array::toHashmap(Country::find('')->getAll()->toArray(),'country','description');
        $this->_view['shipments']=Store_Shipment::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['payments']=Store_Payment::find('store_id=?',$this->store['store_id'])->getAll();
        if(count($this->_view['cart']['goods'])){
            $this->_view['goods']=Goods::find('goods_id in (?)',array_keys($this->_view['cart']['goods']))->getAll();
        }
    }
    
    /***
     *   订单信息  
     **/
    function actionOrder(){
        $this->_view['cart']=$this->_cart();
        $this->_view['shipment']=Shipment::find('shipment_id=?',$this->_view['cart']['shipment'])->getOne();
        $this->_view['payment']=Payment::find('payment_id=?',$this->_view['cart']['shipment'])->getOne();
        if(count($this->_view['cart']['goods'])){
            $this->_view['goods']=Goods::find('goods_id in (?)',array_keys($this->_view['cart']['goods']))->getAll();
        }
//         $this->_cart('status',3);
    }
    /**
     * 支付
     */         
    function actionToPay(){
        $cart=$this->_cart();   
    }
    
    function actionDestroy(){
        $this->_destroy();
        return $this->_redirect(url('cart'));
    }
    /**
     * All Them Can 
     */         
    function actionCoupon(){
        if($this->_coupon(trim($this->_context->post('coupon')))){
            //return $this
        }else{
            
        }
        return $this->_redirect(url('cart'));
    }
    
}